<?php

/**
 * -----------| 工具类:自动生成代码-Ajax请求数据 |-----------
 * @category Bb
 * @package core.autocode
 * @author skygreen skygreen2001@gmail.com
 */
class AutoCodeAjax extends AutoCode
{
    /**
     * View生成tpl所在的应用名称，默认同网站应用的名称
     * @var string
     */
    public static $appName;

    /**
     * 实体数据对象类完整的保存路径
     */
    public static $ajax_dir_full;

    /**
     * 自动生成代码-Ajax api php文件
     *
     * 示例如下:
     *
     *    1.array:array('bb_user_admin','bb_core_blog')
     *
     *    2.字符串:'bb_user_admin,bb_core_blog'
     *
     * @param array|string $table_names
     */
    public static function autoCode($table_names = "")
    {
        self::init();

        self::$app_dir = "admin";
        self::$appName = "admin";


        // self::$showReport .= AutoCodeFoldHelper::foldEffectCommon("Content_41");
        self::$showReport     .= '<div id="Content_41" style="display:none;">';
        self::$ajax_dir_full = self::$save_dir . "api" . DS . "mobile" . DS;

        $link_service_dir_href = "file:///" . str_replace("\\", "/", self::$ajax_dir_full);
        self::$showReport     .= "<font color='#AAA'>存储路径:<a target='_blank' href='" . $link_service_dir_href . "'>" . self::$ajax_dir_full . "</a></font><br/><br/>";

        $fieldInfos = self::fieldInfosByTable_names($table_names);
        foreach ($fieldInfos as $tablename => $fieldInfo) {
            $api_editContent  = AutoCodeAjax::api_mobile_admin($tablename, $fieldInfo);
            $phpName          = AutoCodeAjax::saveApiMobileDefineToDir($tablename, $api_editContent);
            self::$showReport .= "生成导出完成:$tablename => $phpName!<br/>";
        }
        self::$showReport .= "</div><br/>";
    }

    /**
     * 将表列定义转换成表示层js所需Api Web文件定义的内容
     * @param string $tablename 表名
     * @param array $fieldInfo 表列信息列表
     */
    public static function api_mobile_admin($tablename, $fieldInfo)
    {
        $appname      = self::$appName;
        $classname    = self::getClassname($tablename);
        $instancename = self::getInstancename($tablename);
        $realId       = DataObjectSpec::getRealIDColumnName($classname);
        $editApiImg   = "";
        $editApiRela  = "";
        foreach ($fieldInfo as $fieldname => $field) {
            $field_comment = $field["Comment"];
            if (($realId != $fieldname) && self::isNotColumnKeywork($fieldname, $field_comment)) {
                $field_comment    = $field["Comment"];
                $isImage          = self::columnIsImage($fieldname, $field_comment);
                if ($isImage) {
                    $editApiImg  .= "        if (!empty(\${$instancename}->$fieldname)) {" . HH .
                                    "            \${$instancename}->$fieldname = Gc::\$upload_url . \"images/\" . \${$instancename}->$fieldname;" . HH .
                                    "        }" . HH;
                }
                $datatype = self::comment_type($field["Type"]);
                switch ($datatype) {
                    case 'bit':
                        break;
                    case 'enum':
                        break;
                    case 'date':
                        break;
                    default:
                        break;
                }
                $editApiRela = self::relationFieldShow($instancename, $classname, $fieldInfo);
            }
        }
        $classNameField = self::getShowFieldName($classname);
        include("template" . DS . "ajax.php");
        $result = $api_web_template;
        return $result;
    }

    /**
     * 显示关系列
     * @param mixed $instance_name 实体变量
     * @param mixed $classname 数据对象列名
     * @param mixed $fieldInfo 表列信息列表
     */
    protected static function relationFieldShow($instance_name, $classname, $fieldInfo)
    {
        $result = "";
        if (is_array(self::$relation_viewfield) && (count(self::$relation_viewfield) > 0)) {
            if (array_key_exists($classname, self::$relation_viewfield)) {
                $relationSpecs  = self::$relation_viewfield[$classname];
                foreach ($fieldInfo as $fieldname => $field) {
                    if (array_key_exists($fieldname, $relationSpecs)) {
                        $relationShow = $relationSpecs[$fieldname];
                        foreach ($relationShow as $key => $value) {
                            $realId         = DataObjectSpec::getRealIDColumnName($key);
                            $show_fieldname = $value;
                            if ($realId != $fieldname) {
                                $show_fieldname .= "_" . $fieldname;
                                if (contain($show_fieldname, "_id")) {
                                    $show_fieldname = str_replace("_id", "", $show_fieldname);
                                }
                            }
                            if ($show_fieldname == "name") {
                                $show_fieldname = strtolower($key) . "_" . $value;
                            }
                            $i_name = $key;
                            $i_name = lcfirst($i_name);
                            if (!array_key_exists("$show_fieldname", $fieldInfo)) {
                                $result .= "        if (!empty(\${$instance_name}->$fieldname)) {" . HH .
                                           "            \${$i_name}_i = $key::getById(\${$instance_name}->$fieldname);" . HH .
                                           "            if (\${$i_name}_i) {" . HH .
                                           "                \${$instance_name}->$show_fieldname = \${$i_name}_i->$value;" . HH .
                                           "            }" . HH .
                                           "        }" . HH;
                            }
                        }
                    }
                }
            }
        }
        return $result;
    }

    /**
     * 保存生成的api web代码到指定命名规范的文件中
     * @param string $tablename 表名称
     * @param string $defineApiWebFileContent 生成的代码
     */
    public static function saveApiMobileDefineToDir($tablename, $defineApiWebFileContent)
    {
        $classname     = self::getClassname($tablename);
        $instancename  = self::getInstancename($tablename);
        $dir           = self::$ajax_dir_full;
        $filename      = $instancename . ConfigF::SUFFIX_FILE_PHP;
        $relative_path = "api" . DS . "mobile" . DS . $filename;
        AutoCodePreviewReport::$api_admin_files[$classname . $filename] = $relative_path;
        return self::saveDefineToDir($dir, $filename, $defineApiWebFileContent);
    }
}
